import AsyncStorage from '@react-native-community/async-storage';
/*
 * @Author: Yzq
 * @Date: 2021-04-02 15:08:02
 * @LastEditTime: 2021-04-06 18:24:41
 * @LastEditors: Yzq
 */

export interface RememberData {
  username: string;
  pwd: string;
}

export default class User {
  static USER_KEY = 'USER_KEY';
  static LANGUAGE_KEY = 'LANGUAGE_KEY';

  static username: string = '';
  static pwd: string = '';
  //判断登录状态
  static token: boolean = false;
  //判断语言语种
  static isChinese: boolean = true;

  static init = async () => {
    //TODO:1.读取持久化数据，赋值给内存
    return new Promise(async (resolve, reject) => {
      try {
        const res = await AsyncStorage.getItem(this.USER_KEY);
        const jsonRes: RememberData = JSON.parse(res);
        this.username = jsonRes?.username;
        this.pwd = jsonRes?.pwd;
        resolve();
      } catch (error) {
        reject();
      }
    });
  };

  //TODO:持久化token
  static setToken() {}

  //TODO:参考init，但操作的是token
  static initToken() {}

  static storage = (username: string, pwd: string, isLoged: boolean) => {
    this.username = username;
    this.pwd = pwd;
    this.isLoged = isLoged;

    AsyncStorage.setItem(
      this.USER_KEY,
      JSON.stringify({username, pwd, isLoged}),
    );
  };

  static storageLanguage = (isChinese: boolean) => {
    this.isChinese = isChinese;
    AsyncStorage.setItem(this.LANGUAGE_KEY, JSON.stringify(isChinese));
  };

  static clear = () => {
    AsyncStorage.removeItem(this.USER_KEY);
    this.pwd = '';
  };
}
